package com.gitee.cirnochat.common.utils;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.server.reactive.ServerHttpRequest;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Optional;

public final class RequestUtils {
    private RequestUtils() {
        // Prevent instantiation
        throw new UnsupportedOperationException("Utility class");
    }

    private static final String IP_UNKNOWN = "unknown";
    private static final String IP_LOCAL = "127.0.0.1";
    private static final int IP_LEN = 15;

    /**
     * 获取客户端真实ip
     *
     * @param request request
     * @return 返回ip
     */
    public static String getIp(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || IP_UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || IP_UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || IP_UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = Optional.ofNullable(request.getRemoteAddr())
                    .orElse("");
            if (IP_LOCAL.equals(ipAddress)) {
                // 根据网卡取本机配置的IP
                try {
                    InetAddress inet = InetAddress.getLocalHost();
                    ipAddress = inet.getHostAddress();
                } catch (UnknownHostException e) {
                    // ignore
                }
            }
        }
        // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ipAddress != null && ipAddress.length() > IP_LEN) {
            int index = ipAddress.indexOf(",");
            if (index > 0) {
                ipAddress = ipAddress.substring(0, index);
            }
        }
        return ipAddress;
    }

    public static String getVisitHost(HttpServletRequest request) {
        return request.getRemoteHost();
    }

    public static String getAuthorization(ServerHttpRequest request) {
        return request.getHeaders().getFirst("Authorization");
    }
    public static String getUserAgent(HttpServletRequest request) {
        return request.getHeader("User-Agent");
    }

    public static Long getUserId(HttpServletRequest request) {
        return (Long) request.getAttribute("user");
    }
    public static String getDeviceId(HttpServletRequest request) {
        return request.getHeader("X-Device-Id");
    }

    public static String getDeviceName(HttpServletRequest request) {
        return request.getHeader("X-Device-Name");
    }

    public static String getDeviceType(HttpServletRequest request) {
        return request.getHeader("X-Device-Type");
    }

}
